// 直接从models目录导入Grade模型
const { Grade } = require('../models');

// 成绩控制器
const gradeController = {
  // 获取所有成绩
  async getAllGrades(ctx) {
    try {
      const grades = await Grade.find().populate('studentId');
      ctx.body = {
        success: true,
        data: grades,
        count: grades.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取成绩列表失败',
        error: error.message
      };
    }
  },

  // 根据ID获取成绩
  async getGradeById(ctx) {
    try {
      const grade = await Grade.findById(ctx.params.id).populate('studentId');
      if (!grade) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '成绩记录不存在'
        };
        return;
      }
      ctx.body = {
        success: true,
        data: grade
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取成绩信息失败',
        error: error.message
      };
    }
  },

  // 创建成绩记录
  async createGrade(ctx) {
    try {
      const gradeData = ctx.request.body;

      // 创建成绩记录
      const grade = new Grade(gradeData);
      await grade.save();
      
      // 重新获取成绩信息（包含关联数据）
      const newGrade = await Grade.findById(grade._id).populate('studentId');

      ctx.status = 201;
      ctx.body = {
        success: true,
        message: '成绩记录创建成功',
        data: newGrade
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '创建成绩记录失败',
        error: error.message
      };
    }
  },

  // 更新成绩信息
  async updateGrade(ctx) {
    try {
      const grade = await Grade.findById(ctx.params.id);
      if (!grade) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '成绩记录不存在'
        };
        return;
      }

      const updateData = ctx.request.body;
      // 更新成绩信息
      Object.assign(grade, updateData);
      grade.updatedAt = Date.now();
      await grade.save();

      // 重新获取成绩信息（包含关联数据）
      const updatedGrade = await Grade.findById(ctx.params.id).populate('studentId');

      ctx.body = {
        success: true,
        message: '成绩信息更新成功',
        data: updatedGrade
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '更新成绩信息失败',
        error: error.message
      };
    }
  },

  // 删除成绩记录
  async deleteGrade(ctx) {
    try {
      const grade = await Grade.findById(ctx.params.id);
      if (!grade) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '成绩记录不存在'
        };
        return;
      }

      // 删除成绩记录
      await Grade.findByIdAndDelete(ctx.params.id);

      ctx.body = {
        success: true,
        message: '成绩记录删除成功'
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '删除成绩记录失败',
        error: error.message
      };
    }
  },

  // 获取学生的所有成绩
  async getStudentGrades(ctx) {
    try {
      const grades = await Grade.find({ studentId: ctx.params.studentId })
        .sort({ term: -1, subject: 1 });
      
      // 计算平均分
      let totalScore = 0;
      grades.forEach(grade => {
        totalScore += grade.score;
      });
      const averageScore = grades.length > 0 ? (totalScore / grades.length).toFixed(2) : 0;
      
      ctx.body = {
        success: true,
        data: {
          grades,
          averageScore,
          count: grades.length
        }
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取学生成绩失败',
        error: error.message
      };
    }
  },

  // 获取班级的成绩列表
  async getClassGrades(ctx) {
    try {
      // 先获取班级的所有学生ID
      const Student = require('../models/student');
      const students = await Student.find({ classId: ctx.params.classId }, '_id');
      const studentIds = students.map(student => student._id);
      
      // 查询这些学生的成绩
      const grades = await Grade.find({ studentId: { $in: studentIds } })
        .populate('studentId')
        .sort({ term: -1, subject: 1 });
      
      ctx.body = {
        success: true,
        data: grades,
        count: grades.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取班级成绩失败',
        error: error.message
      };
    }
  },

  // 获取科目成绩统计
  async getSubjectStats(ctx) {
    try {
      const { subject } = ctx.params;
      const term = ctx.query.term;
      
      const query = { subject };
      if (term) {
        query.term = term;
      }
      
      const grades = await Grade.find(query);
      
      if (grades.length === 0) {
        ctx.body = {
          success: true,
          data: {
            subject,
            term,
            count: 0,
            average: 0,
            highest: 0,
            lowest: 0,
            passed: 0,
            passRate: '0%'
          }
        };
        return;
      }
      
      // 计算统计信息
      let totalScore = 0;
      let highest = 0;
      let lowest = 150;
      let passed = 0;
      
      grades.forEach(grade => {
        totalScore += grade.score;
        highest = Math.max(highest, grade.score);
        lowest = Math.min(lowest, grade.score);
        if (grade.score >= 60) {
          passed++;
        }
      });
      
      const average = (totalScore / grades.length).toFixed(2);
      const passRate = `${((passed / grades.length) * 100).toFixed(1)}%`;
      
      ctx.body = {
        success: true,
        data: {
          subject,
          term,
          count: grades.length,
          average,
          highest,
          lowest,
          passed,
          passRate
        }
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取科目成绩统计失败',
        error: error.message
      };
    }
  },

  // 根据学期获取成绩
  async getGradesByTerm(ctx) {
    try {
      const grades = await Grade.find({ term: ctx.params.term })
        .populate('studentId')
        .sort({ subject: 1 });
      
      ctx.body = {
        success: true,
        data: grades,
        count: grades.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取学期成绩失败',
        error: error.message
      };
    }
  }
};

module.exports = gradeController;